﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.IO;
using System.Collections;
using Newtonsoft.Json.Linq;

namespace BEX.Core.Exchange.BITSTAMP
{
    public class Bitstamp : Exchange
    {
        public Bitstamp()
            : base(ExchangeType.BITSTAMP)
        {
            
        }

        internal override Tick GetCurrentTick(CurrencyPair pair)
        {

            BitstampResponse response = GetBitstampTick();

            Tick res = new Tick();

            res.Ask = Convert.ToInt32(Convert.ToDecimal(response.ask) * global.ConversionFactor);
            res.Bid = Convert.ToInt32(Convert.ToDecimal(response.bid) * global.ConversionFactor);
            res.Currency = pair;
            res.ExchangeSource = ExchangeType.BITSTAMP;
            res.Time = DateTime.UtcNow;
            res.Spot = Convert.ToInt32(Convert.ToDecimal(response.last) * global.ConversionFactor);

            return res;
        }

        private BitstampResponse GetBitstampTick()
        {
            var queryStr = string.Format(TickerURL, string.Empty);

            var resp = Query(queryStr);

            return new BitstampResponse(JObject.Parse(resp) as JObject);
        }

        private static string Query(string url)
        {
            var request = WebRequest.Create(url);
            request.Method = "GET";
            if (request == null)
            {
                throw new Exception("Non HTTP WebRequest");
            }
            return new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd();
        }

        protected override string _baseUrl
        {
            get { return ExchangeConfig.Default.BitStampAPI_BaseURL; }
        }

        protected override string _tickPath
        {
            get { return ExchangeConfig.Default.BitStampAPI_GetTickPath; }
        }

        protected override string _pairs
        {
            get { return ExchangeConfig.Default.BitStamp_Pairs; }
        }
    }
}
